<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { UserApi } from '@/api-services/apis/user-api';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { REG_PWD, REG_USER_NAME } from '@/constants/reg';
import { ApiroleserviceApi } from '@/api-services/apis/apiroleservice-api';
import { NetoKit } from '@/typings/neto';
import { ApiSysNoticeInput, SysemailsendrecordApi } from '@/api-services';
import { SysnoticeApi } from '@/api-services/apis/sysnotice-api';
import dayjs, { Dayjs } from 'dayjs';

defineOptions({
  name: 'SysManageSysNoticeModal'
});

interface Props {
  /** the type of operation */
  operateType: UI.TableOperateType;
  /** the edit row data */
  editId?: number | undefined;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation} = useForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    //新建通知
    add: $t('page.sysNotice.addTitle'),
    //编辑通知
    edit: $t('page.sysNotice.editTitle')
  };
  return titles[props.operateType];
});

// const regs: Record<UI.TableOperateType, App.Global.FormRule> = {
//   edit: { required: false },
//   add: {
//     required: true,
//     pattern: REG_PWD,
//     message: $t('form.pwd.invalid'),
//     trigger: 'change'
//   }
// };

// type Model = NonNullable<Pick<
//   ApiUserOut,
//   'account' | 'nick' | 'phone' | 'email' | 'isEnable'
// >>;
type Model = NetoKit.IsNonNullable<{
  [K in keyof Pick<ApiSysNoticeInput,
    'id' | 'noticeType' | 'noticeState' | 'noticeContent' | 'noticeResult' |
    'maxCount' | 'noticeCount' | 'totalUserCount' | 'readUserCount'|'title'>]: ApiSysNoticeInput[K];
}> & { completedTime: Date | undefined; nextNoticeTime: Date | undefined; lastNoticeTime: Date | undefined; }
const model = ref(createDefaultModel());
// string转换为number
// model.value.roleIds = model.value.roleIdStr?.split(',').map(Number);
function createDefaultModel(): Model {
  return {
    id: 0,
    title: '',
    noticeType: 0,
    noticeState: 0,
    noticeContent: '',
    noticeResult: '',
    completedTime: undefined,
    nextNoticeTime: undefined,
    lastNoticeTime: undefined,
    maxCount: 0,
    noticeCount: 0,
    totalUserCount: 0,
    readUserCount: 0,
  }
}



async function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.editId) {
    const [err, res] = await feature(getAPI(SysnoticeApi).get(props.editId));
    queryDone(err, () => {
      const data = res?.data.data;
      if (data) {
        Object.assign(model.value, data);
        // //初始化时间
        // if (data.completedTime) {
        //   model.value.completedTimeDayjs = dayjs(data.completedTime);
        // }

        // if (data.nextNoticeTime) {
        //   model.value.nextNoticeTimeDayjs = dayjs(data.nextNoticeTime);
        // }

        // if (data.lastNoticeTime) {
        //   model.value.lastNoticeTimeDayjs = dayjs(data.lastNoticeTime);
        // }


      }
    })
  }
}

function closeModal() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();


  const input: ApiSysNoticeInput = {
    ...model.value
  }

  // if (model.value.completedTimeDayjs) {
  //   input.completedTime = dayjs(model.value.completedTimeDayjs).toDate();
  // }
  // if (model.value.nextNoticeTimeDayjs) {
  //   input.nextNoticeTime = dayjs(model.value.nextNoticeTimeDayjs).toDate();
  // }
  // if (model.value.lastNoticeTimeDayjs) {
  //   input.lastNoticeTime = dayjs(model.value.lastNoticeTimeDayjs).toDate();
  // }




  if (props.operateType === 'add') {
    const [err, res] = await feature(getAPI(SysnoticeApi).insert(input));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.addSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  } else {
    const [err, res] = await feature(getAPI(SysnoticeApi).update(input));

    queryDone(err, async () => {
      if (res?.data.data) {
        window.$message?.success($t('common.updateSuccess'));
        closeModal();
        emit('submitted');
      }
    });
  }

}
type RuleKey = Extract<keyof Model, 'emailSmtpHost' | 'emailSmtpPort' | 'emailAccount' | 'sendMode'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  emailSmtpHost: defaultRequiredRule,
  emailSmtpPort: defaultRequiredRule,
  emailAccount: defaultRequiredRule,
  sendMode: defaultRequiredRule
};

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    // getRoleOptions();
  }
});
</script>

<template>
  <NModal v-model:open="visible" :title="title"  width="1000px">
    <ElForm ref="formRef" label-width="auto" :model="model" :rules="rules">
      <ElRow :gutter="16" wrap>
              <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.title')" name="title">
            <ElInput v-model="model.title"  style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <!-- 系统通知类型 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.noticeType')" name="noticeType">
            <ElSelect v-model="model.noticeType">
              <!-- 系统通知 -->
              <ElOption :value="0" :label="$t('page.sysNotice.noticeTypeEnum.systemNotice')"/>
              <!-- 系统公告 -->
              <ElOption :value="1" :label="$t('page.sysNotice.noticeTypeEnum.systemBulletin')"/>
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 通知状态 -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.noticeState')" name="noticeState">
            <ElSelect v-model="model.noticeState">
              <ElOption :value="0" :label="$t('page.sysNotice.noticeStateEnum.pending') "/>
              <ElOption :value="1" :label="$t('page.sysNotice.noticeStateEnum.succeeded')"/>
              <ElOption :value="2" :label="$t('page.sysNotice.noticeStateEnum.failed')"/>
              <ElOption :value="1001" :label=" $t('page.sysNotice.noticeStateEnum.noNotificationAddress')"/>
              <ElOption :value="1002" :label="$t('page.sysNotice.noticeStateEnum.notificationDisabled')"/>
            </ElSelect>
          </ElFormItem>
        </ElCol>

        <!-- 通知内容（全宽） -->
        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.noticeContent')" name="noticeContent">
            <NEditor v-model="model.noticeContent" />
          </ElFormItem>
        </ElCol>

        <!-- 通知结果 -->
        <ElCol :lg="24" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.noticeResult')" name="noticeResult">
            <ElInput type="textarea" v-model="model.noticeResult" :auto-size="{ minRows: 3 }" />
          </ElFormItem>
        </ElCol>

        <!-- 时间相关（日期选择器） -->
        <ElCol :lg="8" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.completedTime')" name="completedTime">
            <ElDatePicker v-model="model.completedTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="8" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.nextNoticeTime')" name="nextNoticeTime">
            <ElDatePicker v-model="model.nextNoticeTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="8" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.lastNoticeTime')" name="lastNoticeTime">
            <ElDatePicker v-model="model.lastNoticeTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%" />
          </ElFormItem>
        </ElCol>

        <!-- 数字输入（使用 InputNumber） -->
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.maxCount')" name="maxCount">
            <ElInputNumber v-model="model.maxCount" :min="0" style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.noticeCount')" name="noticeCount">
            <ElInputNumber v-model="model.noticeCount" :min="0" style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.totalUserCount')" name="totalUserCount">
            <ElInputNumber v-model="model.totalUserCount" :min="0" style="width: 100%" />
          </ElFormItem>
        </ElCol>
        <ElCol :lg="12" :xs="24">
          <ElFormItem :label="$t('page.sysNotice.readUserCount')" name="readUserCount">
            <ElInputNumber v-model="model.readUserCount" :min="0" style="width: 100%" />
          </ElFormItem>
        </ElCol>

      </ElRow>

    </ElForm>
    <template #footer>
      <ElSpace :size="16">
        <ElButton @click="closeModal">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
